package com.example.glkotlin

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.Toast

/**
 * with run 和 apply函数的区别
 * with(obj,{}) obj.function
 * obj.run{} : obj.function
 * obj.apply : obj
 *
 * 静态方法的几种写法
 * 1. 单例类  object class   模拟静态   加上@JvmStatic 变成真正的静态
 * 2. companion object { fun ()}    模拟静态  加上@JvmStatic 变成真正的静态
 * 3. 顶层方法   建立一个kotlin文件，直接定义方法 kotlin自动生成对应的静态类
 *
 */
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // kotlin-android-extensions 这个插件已经被弃用了，推荐viewBinding，所以还是先findViewById
        val button = findViewById<Button>(R.id.button)
        button.setOnClickListener{
            Toast.makeText(this, "The button is clicked", Toast.LENGTH_SHORT).show()
//            val intent = Intent(this, HomeActivity::class.java)
            val intent = Intent(this, MessageActivity::class.java)
            intent.putExtra("data", "Nice to meet you!")
//            startActivity(intent)
            startActivityForResult(intent, 1)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId) {
            R.id.add_item ->
                Toast.makeText(this, "add is clicked", Toast.LENGTH_SHORT).show()
            R.id.remove_item ->
                Toast.makeText(this, "remove is clicked", Toast.LENGTH_SHORT).show()
        }
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode) {
            1 -> if (RESULT_OK == resultCode) {
                val dataReturn : String? = data?.getStringExtra("data_return")
                Toast.makeText(this, dataReturn , Toast.LENGTH_SHORT).show()
                Log.d(TAG, "onActivityResult data = ${dataReturn}")
            }
        }
    }

    companion object {
        private const val TAG = "MainActivity"
    }
}